<template>
  <div class="config-attribute-manage">
    <!-- 物模型协议 - 配置属性管理页面 -->
    <!-- 面包屑导航 -->
    <el-card class="breadcrumb-card" shadow="never" style="margin-bottom: 8px;">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>{{ dataFormatInfo.protocolName || '协议列表' }}</el-breadcrumb-item>
        <el-breadcrumb-item>{{ dataFormatInfo.name || '数据格式管理' }}</el-breadcrumb-item>
        <el-breadcrumb-item>配置属性管理</el-breadcrumb-item>
      </el-breadcrumb>
    </el-card>



    <!-- 操作按钮区域 -->
    <!-- <el-card class="operation-card" shadow="never" style="margin-bottom: 8px;">
      <div class="operation-buttons">
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
        <el-button type="danger" :icon="Delete" :disabled="selectedRows.length === 0" @click="handleBatchDelete">
          批量删除
        </el-button>
        <el-button type="warning" :icon="Download" @click="handleExport">导出</el-button>
        <el-button type="info" :icon="ArrowLeft" @click="handleBack">返回</el-button>
      </div>
    </el-card> -->

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="selectedRows.length === 0"
            @click="handleDelete(false)">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="ArrowLeft" @click="handleBack">返回</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="tableData" :loading="loading" @selection-change="handleSelectionChange" stripe border
        style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="propertyId" label="属性ID" min-width="100" />
        <el-table-column prop="dataformatId" label="数据格式ID" min-width="120" />
        <el-table-column prop="propertyType" label="属性类型" min-width="120">
          <template #default="{ row }">
            <el-tag :type="getPropertyTypeTagType(row.propertyType)">
              {{ getPropertyTypeText(row.propertyType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="属性名称" min-width="120" />
        <el-table-column prop="identifier" label="属性标识符" min-width="120" />
        <el-table-column prop="number" label="属性编号" min-width="100" />
        <el-table-column prop="required" label="是否必选" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getRequiredTagType(row.required)">
              {{ getRequiredText(row.required) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dataType" label="数据类型" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getDataTypeTagType(row.dataType)">
              {{ getDataTypeText(row.dataType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dataValue" label="数据值" min-width="120" />
        <el-table-column prop="unit" label="数据单位" min-width="100" />
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="120" />
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon>
                <Edit />
              </el-icon>
              编辑
            </el-button>

            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon>
                <Delete />
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination class="pagination" v-model:current-page="currentPage" v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
      <!-- <div class="pagination-section">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.size"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div> -->
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <ConfigAttributeFormDialog v-model:visible="formDialogVisible" :title="isEdit ? '编辑配置属性' : '新增配置属性'"
      :data="currentRow" :loading="submitLoading" @submit="handleFormSubmit" @cancel="handleFormCancel" />
  </div>




</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import {
  Plus,
  Upload,
  Download,
  ArrowLeft,
  View,
  Edit,
  Delete
} from '@element-plus/icons-vue'
// 采用本地模拟数据，移除远程API导入
import type {
  ConfigAttributeInfo,
  ConfigAttributeQuery,
  ConfigAttributeFormData,
  ConfigAttributePageResult
} from '@/api/IOT/protocolManage/configAttributeManage/types'
import ConfigAttributeFormDialog from './components/ConfigAttributeFormDialog.vue'


const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const selectedRows = ref<ConfigAttributeInfo[]>([])

// 弹窗状态
const formDialogVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const currentRow = ref<ConfigAttributeInfo | null>(null)

// 数据格式信息
const dataFormatInfo = reactive({
  id: '',
  name: '',
  protocolId: '',
  protocolName: '',
  protocolVersionId: '',
  productId: '',
  productName: '',
  categoryId: '',
  categoryName: ''
})



// 表格数据
const tableData = ref<ConfigAttributeInfo[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 查看数据
const viewData = ref<ConfigAttributeInfo | null>(null)

// 工具函数
// 属性类型文本转换
const getPropertyTypeText = (type: number) => {
  const typeMap: Record<number, string> = {
    0: '运行参数',
    1: '健康参数',
    2: '辅助参数'
  }
  return typeMap[type] || '未知'
}

// 属性类型标签类型
const getPropertyTypeTagType = (type: number) => {
  const typeMap: Record<number, string> = {
    0: 'primary',
    1: 'success',
    2: 'warning'
  }
  return typeMap[type] || ''
}

// 是否必选文本转换
const getRequiredText = (required: number) => {
  return required === 1 ? '是' : '否'
}

// 是否必选标签类型
const getRequiredTagType = (required: number) => {
  return required === 1 ? 'success' : 'info'
}

// 数据类型文本转换
const getDataTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'bool': '布尔值',
    'int32': '32位整数',
    'float': '浮点数',
    'double': '双精度浮点数',
    'text': '文本',
    'enum': '枚举',
    'json': 'JSON',
    'array': '数组',
    'bytes': '字节'
  }
  return typeMap[type] || type
}

// 数据类型标签类型
const getDataTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    'bool': 'warning',
    'int32': 'primary',
    'float': 'success',
    'double': 'success',
    'text': 'info',
    'enum': 'warning',
    'json': 'danger',
    'array': 'info',
    'bytes': 'danger'
  }
  return typeMap[type] || ''
}

// 状态文本转换
const getStatusText = (status: number) => {
  return status === 1 ? '启用' : '停用'
}

// 状态标签类型
const getStatusTagType = (status: number) => {
  return status === 1 ? 'success' : 'danger'
}

// 方法

const handleAdd = () => {
  isEdit.value = false
  currentRow.value = {
    protocolVersionId: dataFormatInfo.protocolVersionId,
    dataformatId: dataFormatInfo.id
  } as ConfigAttributeInfo
  formDialogVisible.value = true
}

const handleEdit = (row: ConfigAttributeInfo) => {
  isEdit.value = true
  currentRow.value = { ...row }
  formDialogVisible.value = true
}


const handleFormSubmit = async (data: ConfigAttributeFormData) => {
  try {
    submitLoading.value = true
    await delayRandom()
    if (isEdit.value && currentRow.value?.id) {
      // 编辑模式（本地模拟）
      const idx = allConfigAttributes.value.findIndex(item => String(item.id) === String(currentRow.value!.id))
      if (idx !== -1) {
        allConfigAttributes.value[idx] = {
          ...allConfigAttributes.value[idx],
          ...data
        } as ConfigAttributeInfo
        ElMessage.success('修改成功')
      } else {
        ElMessage.error('未找到该配置属性')
        return
      }
    } else {
      // 新增模式（本地模拟）
      const newIdNum = Math.max(0, ...allConfigAttributes.value.map(item => Number(String(item.id).replace(/^CA/, '')))) + 1
      const newItem: ConfigAttributeInfo = {
        id: 'CA' + String(newIdNum).padStart(4, '0'),
        dataformatId: dataFormatInfo.id,
        propertyId: 'P' + String(newIdNum).padStart(3, '0'),
        status: 1,
        remark: '',
        ...data
      } as ConfigAttributeInfo
      allConfigAttributes.value.unshift(newItem)
      ElMessage.success('新增成功')
    }
    formDialogVisible.value = false
    loadData()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handleFormCancel = () => {
  formDialogVisible.value = false
  currentRow.value = null
}

const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 条配置属性吗？`, '批量删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    loading.value = true
    await delayRandom()
    const ids = selectedRows.value.map(row => String(row.id))
    allConfigAttributes.value = allConfigAttributes.value.filter(item => !ids.includes(String(item.id)))
    selectedRows.value = []
    ElMessage.success('批量删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  } finally {
    loading.value = false
  }
}

const handleExport = async () => {
  try {
    loading.value = true
    await delayRandom()
    const headers = ['属性ID', '数据格式ID', '属性类型', '属性名称', '属性标识符', '属性编号', '是否必选', '数据类型', '数据值', '数据单位', '状态', '备注']
    const rows = tableData.value.map(row => [
      row.propertyId,
      row.dataformatId,
      getPropertyTypeText(row.propertyType),
      row.name,
      row.identifier,
      row.number,
      getRequiredText(row.required),
      row.dataType,
      row.dataValue,
      row.unit,
      getStatusText(row.status),
      row.remark || ''
    ])
    const csv = [headers.join(','), ...rows.map(r => r.join(','))].join('\n')
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `配置属性列表_${new Date().getTime()}.csv`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

const handleDelete = async (row: ConfigAttributeInfo | boolean) => {
  if (typeof row === 'boolean') {
    // 批量删除
    return handleBatchDelete()
  }
  try {
    await ElMessageBox.confirm(`确定要删除配置属性\"${row.name}\"吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    loading.value = true
    await delayRandom()
    allConfigAttributes.value = allConfigAttributes.value.filter(item => String(item.id) !== String(row.id))
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  } finally {
    loading.value = false
  }
}

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadData()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadData()
}

const handleBack = () => {
  goBackToDataFormat()
}

const loadData = async () => {
  try {
    loading.value = true
    await delayRandom()
    // 本地过滤与分页
    const filtered = allConfigAttributes.value.filter(item => String(item.dataformatId) === String(dataFormatInfo.id))
    total.value = filtered.length
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    tableData.value = filtered.slice(start, end)
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const goBackToDataFormat = () => {
  router.back();
}

// 模拟网络延迟（0~1500ms）
const delayRandom = (min = 200, max = 1500) => new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * (max - min + 1)) + min))

// 本地模拟的数据源：配置属性列表
const allConfigAttributes = ref<ConfigAttributeInfo[]>([
  { id: 'CA0001', dataformatId: 'DF1001', propertyId: 'P001', propertyType: 0, name: '运行模式', identifier: 'run_mode', number: '001', required: 1, dataType: 'enum', dataValue: 'auto,manual', unit: '', status: 1, remark: '自动/手动模式', protocolVersionId: 'PV1001' },
  { id: 'CA0002', dataformatId: 'DF1001', propertyId: 'P002', propertyType: 1, name: '设备温度', identifier: 'device_temp', number: '002', required: 1, dataType: 'float', dataValue: '36.5', unit: '℃', status: 1, remark: '', protocolVersionId: 'PV1001' },
  { id: 'CA0003', dataformatId: 'DF1002', propertyId: 'P003', propertyType: 2, name: '心跳间隔', identifier: 'heartbeat_interval', number: '003', required: 1, dataType: 'int32', dataValue: '30', unit: 's', status: 1, remark: '', protocolVersionId: 'PV1001' },
  { id: 'CA0004', dataformatId: 'DF1004', propertyId: 'P004', propertyType: 0, name: '同步开关', identifier: 'sync_enable', number: '004', required: 0, dataType: 'bool', dataValue: 'true', unit: '', status: 0, remark: '是否开启同步', protocolVersionId: 'PV1002' }
])

// 初始化数据格式信息（从路由参数）
const initDataFormatInfo = () => {
  const { formatId, formatName, protocolId, protocolName, protocolVersionId, productId, productName, categoryId, categoryName } = route.query as Record<string, string>
  if (formatId && formatName) {
    Object.assign(dataFormatInfo, {
      id: formatId,
      name: formatName,
      protocolId: protocolId || '',
      protocolName: protocolName || '',
      protocolVersionId: protocolVersionId || '',
      productId: productId || '',
      productName: productName || '',
      categoryId: categoryId || '',
      categoryName: categoryName || ''
    })
  }
}

onMounted(() => {
  initDataFormatInfo()
  loadData()
})
</script>

<style scoped>
.config-attribute-manage {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-section {
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  width: 100%;
}

.operation-section {
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.operation-buttons {
  display: flex;
  gap: 8px;
}

.table-section {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}


.mr-1 {
  margin-right: 4px;
}

.breadcrumb {
  display: flex;
}

.enum-values {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}

.enum-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.enum-item:last-child {
  margin-bottom: 0;
}
</style>